import { createSlice } from "@reduxjs/toolkit";
import { get_token, remove_token, set_token } from "../../utils/auth";
import { logins } from "../../service/login";

const loginSlice = createSlice({
    name: "login",
    initialState: {
        token: get_token() || "",
        user: {
            name: "",
            photo: "",
            account: ""
        }
    }, reducers: {
        setToken(state, actions) {
            state.token = actions.payload;
            set_token(state.token);
        },
        setUser(state, actions) {
            state.user = actions.payload;

        },
        loginOut(state) {
            state.user = {
                name: "",
                photo: "",
                account: ""
            }

            remove_token();
        }
    }
})

const { setToken, setUser,loginOut } = loginSlice.actions;

//登录
const loginAsync = (obj) => {
    return async (dispatch) => {
        const res = await logins(obj);
        if (res.code == 0) {
            dispatch(setToken(res.data.token));
        }

        return res;
    }

}

export { loginAsync, setUser,loginOut }


export default loginSlice.reducer;